import sensor,image,lcd,time
import KPU as kpu
lcd.init(freq=15000000)
sensor.reset(dual_buff=1)
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.set_hmirror(1)
sensor.set_vflip(1)
sensor.set_windowing((224, 224))
sensor.set_brightness(2)
sensor.set_auto_gain(1)

sensor.run(1)
clock = time.clock()
#classes =['Apple','Lemon','Orange','Peach']
classes = ['apple','kiwifruit']
task = kpu.load(0x300000)
#anchor = (2.78, 2.86, 2.87, 3.02, 3.3, 3.4, 3.44, 3.68, 3.7, 3.81)
anchor = (2.73, 2.89, 3.36, 3.45, 4.06, 4.15, 4.48, 4.53, 4.9, 5.05)
a = kpu.init_yolo2(task, 0.5, 0.3, 5, anchor)
while(True):
    clock.tick()
    img = sensor.snapshot()
    code = kpu.run_yolo2(task, img)
    print(clock.fps())
    fps =clock.fps()
    img.draw_string(2,2, ("%2.1ffps" %(fps)), color=(255,0,0), scale=2)
    if code:
        for i in code:
            a=img.draw_rectangle(i.rect())
            a = lcd.display(img)
            print(i.classid(),i.value())
            for i in code:
                lcd.draw_string(i.x(), i.y(), classes[i.classid()], lcd.RED, lcd.WHITE)
                lcd.draw_string(i.x(), i.y()+12, '%.2f'%i.value(), lcd.RED, lcd.WHITE)
    else:
        a = lcd.display(img)
a = kpu.deinit(task)


#sensor.run(1)
#clock = time.clock()
#classes = ['Apple','Lemon','Orange','Peach']
#task = kpu.load(0x300000)
##task = kpu.load('/sd/1.kmodel')
#anchor = (2.78, 2.86, 2.87, 3.02, 3.3, 3.4, 3.44, 3.68, 3.7, 3.81)


#import sensor, image, lcd, time
#import KPU as kpu
#lcd.init()
#lcd.clear()

#sensor.reset()
#sensor.set_pixformat(sensor.RGB565)
#sensor.set_framesize(sensor.QVGA)
#sensor.set_windowing((224, 224))
#sensor.set_hmirror(0)
#sensor.set_vflip(0)
#sensor.run(1)
#labels=['Apple','Lemon','Orange','Peach']
#task = kpu.load(0x300000)
#lcd.clear(0xFFFF)
#clock = time.clock()
#while(True):
    #img = sensor.snapshot()
    #clock.tick()
    #fmap = kpu.forward(task, img)
    #fps=clock.fps()
    #plist=fmap[:]
    #pmax=max(plist)
    #max_index=plist.index(pmax)
    #a = lcd.display(img, oft=(48,0))
    #lcd.draw_string(48, 224, "%.2f:%s--------------"%(pmax, labels[max_index]),lcd.RED,  lcd.WHITE)
    #print(fps)
#a = kpu.deinit(task)

